package com.icesoft.system.service.impl;

import com.icesoft.framework.core.service.impl.BaseServiceImpl;
import com.icesoft.framework.core.util.TreeUtil;
import com.icesoft.system.entity.*;
import com.icesoft.system.mapper.UserMapper;
import com.icesoft.system.service.UserService;
import com.icesoft.system.vo.MenuVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * userService业务层处理
 *
 * @author madiao
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

	private final UserRoleServiceImpl userRoleService;

	private final PermissionServiceImpl permissionService;

	private final RoleMenuServiceImpl roleMenuService;

	private final MenuServiceImpl menuService;

	public List<Permission> getPermission(Serializable id) {
		List<Long> roleIds = new ArrayList<>();
		for (UserRole userRole : userRoleService.lambdaQuery().eq(UserRole::getUserId, id).list()) {
			roleIds.add(userRole.getRoleId());
		}
		return permissionService.lambdaQuery().in(Permission::getRoleId, roleIds).list();
	}

	public List<MenuVO> getMenu(Serializable id) {
		List<Long> roleIds = new ArrayList<>();
		for (UserRole userRole : userRoleService.lambdaQuery().eq(UserRole::getUserId, id).list()) {
			roleIds.add(userRole.getRoleId());
		}
		if (roleIds.isEmpty()) {
			return new ArrayList<>();
		}
		List<Long> menuIds = new ArrayList<>();
		for (RoleMenu roleMenu : roleMenuService.lambdaQuery().in(RoleMenu::getRoleId, roleIds).list()) {
			menuIds.add(roleMenu.getMenuId());
		}
		if (menuIds.isEmpty()) {
			return new ArrayList<>();
		}
		List<Menu> entityList = menuService.lambdaQuery().in(Menu::getId, menuIds).list();
		return TreeUtil.formatTree(entityList, MenuVO.class);
	}

}
